package com.zhuiyun.project.util;

/**
 * @ClassName WxDecryptUtills
 * @Description TODO
 * @Author kdj
 * @Date 2023/6/17 16:20
 **/

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.*;

/**
 * @author qyb
 * @version 1.0
 * @date 2023/3/13-9:38
 */
public class WxDecryptUtills {
    public static boolean initialized = false;


    /**
     * Adds a provider to the next position available.
     */
    public static void initialize() {
        if (initialized) return;
        // Construct a new provider.  This should only be required when
        // using runtime registration of the provider using the
        Security.addProvider(new BouncyCastleProvider());
        initialized = true;
    }

    // iv处理
    public static AlgorithmParameters generateIV(byte[] iv) throws Exception{
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(iv));
        return params;
    }

    /**
     * AES解密
     * @param content 密文
     * @param keyByte sessionKey
     * @param ivByte iv
     * @return 解密json数据
     */
    public static byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte)  {
        initialize();
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            Key sKeySpec = new SecretKeySpec(keyByte, "AES");
            // cipher 初始化
            cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(ivByte));
            return cipher.doFinal(content);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 微信小程序用户信息解密
     * @param encryptedData 加密数据
     * @param sessionKey    会话密钥
     * @param iv            向量
     * @return {@link String}
     */
    public static String decrypt(String encryptedData, String sessionKey, String iv){
        try {
            byte[] resultByte = decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(sessionKey), Base64.decodeBase64(iv));
            if(null != resultByte && resultByte.length > 0){
                return new String(resultByte, StandardCharsets.UTF_8);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
